package demo1;

import java.util.Stack;

// 最小栈
class MinStack {
    //一个存放数据
    //另一个放最小值
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        this.stack = new Stack<>();
        this.minStack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        if (minStack.empty()) {
            minStack.push(val);
        } else {
            //小于等于栈顶元素  压栈
            if (val <= minStack.peek()) {
                minStack.push(val);
            }
        }
    }

    public void pop() {
        if (!stack.empty()) {
            Integer val = stack.pop();
            //等于minStack栈顶元素时，出栈
            if (val.equals(minStack.peek())) {
                minStack.pop();
            }
        }
    }

    public int top() {
        if (!stack.empty()) {
            return stack.peek();
        }
        return -1;
    }

    public int getMin() {
        if (!minStack.empty()) {
            return minStack.peek();
        }
        return -1;
    }
}
